home *** CD-ROM | disk | FTP | other *** search
- Path: news.mistral.co.uk!usenet
- From: alanc@mistral.co.uk (Alan Campbell)
- Newsgroups: comp.lang.c++
- Subject: Any way to restrict casting?
- Date: Wed, 21 Feb 1996 18:12:43 GMT
- Organization: Me! Organized?, I don't think so!
- Message-ID: <4gfuj4$1cu@news.mistral.co.uk>
- NNTP-Posting-Host: l74.mistral.co.uk
- X-Newsreader: Forte Free Agent 1.0.82
-
- Using Borland C++ 3.1, I find I can coerce a pointer to an instance of
- a class into a pointer to *anything*. Like an int.
-
- e.g.:
-
- #include <iostream.h>
- #include <string.h>
-
- class Base {
-
- public:
- int iFieldb;
- char cFieldb;
- char sFieldb[10];
-
- };
-
- class Derived: public Base {
-
- public:
- int iFieldd;
- char cFieldd;
- char sFieldd[10];
- };
-
-
- int main()
- {
-
- Base aBase;
- Derived aDerived;
-
- aBase.iFieldb = 10;
- aBase.cFieldb = 'a';
- strcpy(aBase.sFieldb,"abcdefghi");
-
- aDerived.iFieldd = 210;
- aDerived.cFieldd = 'ba';
- strcpy(aDerived.sFieldd,"jklmnopqr");
-
- Base* ptrBase = &aBase;
- cout << "aDerived's sFieldb: " << ptrBase->sFieldb << endl;
-
- Derived* ptrDerived = &aDerived;
- cout << "aDerived's sFieldd: " << ptrDerived->sFieldd << endl;
-
- // this is stupid, but it works
-
- ptrDerived = (Derived*) ptrBase;
-
- cout << "aBase's sFieldd, treated as a Derived: " <<
- ptrDerived->sFieldd << endl;
-
- int anInt;
-
- // this is even stupider; taking a data member of an int!
-
- ptrDerived = (Derived*) &anInt;
- cout << "anInt's sFieldd, treated as a Derived: " <<
- ptrDerived->sFieldd << endl;
-
- return 1;
-
- };
-
- Is this valid in all dialects of C++? Is it part of the standard? If
- so, ouch.
-
- Yours,
-
- Alan Campbell
- Brighton, UK
-
- <<<<<<<<<<<<<<<<<<<<<< >>>>>>>>>>>>>>>>>>>
-
-